# -*- coding: utf-8 -*-
import logging
import os,sys
import hashlib
import base64
from simplejson import dumps
from pylons import request, response, session, tmpl_context as c, url, app_globals as g
from pylons.controllers.util import abort, redirect
from afpy.ldap import custom as ldap
from craneserver.lib.base import BaseController, render
from pylons import config
#import eventlet
#from eventlet import patcher
#send_task = patcher.import_patched('celery.execute').send_task
#from celery.execute import send_task
LDAP_CONFIG = config.get('ldap.config')
TEMPLATE_PATH = config.get('ldap.template.path')
allsites = config.get('crane.sites').split(",")
#UID_NUMBER_DN = "cn=uidNext,dc=crane,dc=hust,dc=edu"
log = logging.getLogger(__name__)

class UsersController(BaseController):
    """REST Controller styled on the Atom Publishing Protocol"""
    # To properly map this controller, ensure your config/routing.py
    # file has a resource setup:
    #     map.resource('user', 'users')

    def index(self):
        """GET /users: All items in the collection"""



    def create(self):
        """POST /users: Create a new item"""
        # url('users')
        passwd = str(request.params['password'])
        confirm = str(request.params['confirm'])
        if passwd != confirm:
            return dumps("wrong password")
        sn = str(request.params['lastName'])
        givenName = str(request.params['firstName'])
        uid = str(request.params['username'])
        enable_iaas = bool(request.params['enableIaaS'])
        enable_hpc_paas = bool(request.params['enableHPC'])
        enable_web_paas = bool(request.params['enableWebHosting'])
        #xiebo
        for each in allsites:
            result,id = g.command_queue.execute_wait("iaas.user_create",user=uid,site=each)
            if result is not True:
                return dumps("add user to %s failure" % each)

        md5 = hashlib.md5()
        md5.update(passwd)
        MDPasswd = base64.encodestring(md5.digest()).replace('\n','')
        print sn,givenName,uid,passwd,MDPasswd,enable_iaas
        f_add = file(TEMPLATE_PATH+"user.template","r+")
        userTemplate = f_add.read()
        f_add.close()
        print userTemplate
        userLdif = userTemplate % (uid,givenName,sn,givenName,uid,sn,uid,MDPasswd)
        strTemp = userLdif.splitlines()[0]
        userDN =(strTemp.split(":")[1]).strip()

        ldapConfigFile = file(LDAP_CONFIG,"r")
        ldapConfig = ldapConfigFile.read()
        ldapConfigFile.close()
        print ldapConfig
        index = ldapConfig.find("ldap.bind_dn")
        index1 = ldapConfig.find("ldap.bind_pwd")
        index2 = ldapConfig.find("ldap.uid_number_dn")
        temp = ldapConfig[index:index1-1]
        bind_dn = temp[temp.find("=")+1:].strip()
        temp = ldapConfig[index1:]
        bind_pwd = temp[temp.find("=")+1:temp.find("\n")].strip()
        temp = ldapConfig[index2:]
        uid_number_dn = temp[temp.find("=")+1:temp.find("\n")].strip()
        print bind_pwd,bind_dn,uid_number_dn

        print userDN
        print userLdif
        result = os.system("printf  \"" + userLdif + "\" | ldapadd -x -D \""+ bind_dn + "\" -w " + bind_pwd)

        if result == 0:
            if enable_iaas != False:
                f_iaas_role = file(TEMPLATE_PATH+"iaasRole.template","r+")
                iaasRoleTemplate = f_iaas_role.read()
                f_iaas_role.close()
                print iaasRoleTemplate
                iaasRole = iaasRoleTemplate % userDN
                print iaasRole
                res = os.system("printf  \"" + iaasRole + "\" | ldapmodify -x -D \""+ bind_dn + "\" -w " + bind_pwd)
               
                
                if res != 0:
                    os.system("ldapdelete -x -D \""+ bind_dn + "\" -w " + bind_pwd + "\"" + userDN +"\""  )
                    return dumps("iaas falure")

            if enable_hpc_paas != False:
                f_hpc_role = file(TEMPLATE_PATH+"HPCRole.template","r+")
                hpcRoleTemplate = f_hpc_role.read()
                f_hpc_role.close()
                print hpcRoleTemplate
                hpcRole = hpcRoleTemplate % userDN
                print hpcRole
                res = os.system("printf  \"" + hpcRole + "\" | ldapmodify -x -D \""+ bind_dn + "\" -w " + bind_pwd)
                if res != 0:
                    if enable_iaas != False:
                        delIaasFile = file(TEMPLATE_PATH+"delIaasRole.template","r+")
                        delIaasTemplate = delIaasFile.read()
                        delIaasFile.close()
                        delIaasRole = delIaasTemplate % userDN
                        os.system("printf  \"" + delIaasRole + "\" | ldapmodify -x -D \""+ bind_dn + "\" -w " + bind_pwd)
                    os.system("ldapdelete -x -D \""+ bind_dn + "\" -w " + bind_pwd + "\"" + userDN +"\"")
                    return dumps("hpc failure")

            if enable_web_paas != False:
                f_web_role = file(TEMPLATE_PATH+"WebRole.template","r+")
                webRoleTemplate = f_web_role.read()
                f_web_role.close()
                print webRoleTemplate
                webRole = webRoleTemplate % userDN
                print webRole
                res = os.system("printf  \"" + webRole + "\" | ldapmodify -x -D \""+ bind_dn + "\" -w " + bind_pwd)
                if res != 0:
                    if enable_hpc_paas != False:
                        delHPCFile = file(TEMPLATE_PATH+"delHPCRole.template","r+")
                        delHPCTemplate = delHPCFile.read()
                        delHPCFile.close()
                        delHPCRole = delHPCTemplate % userDN
                        os.system("printf  \"" + delHPCRole + "\" | ldapmodify -x -D \""+ bind_dn + "\" -w " + bind_pwd)

                    if enable_iaas != False:
                        delIaasFile = file(TEMPLATE_PATH+"delIaasRole.template","r+")
                        delIaasTemplate = delIaasFile.read()
                        delIaasFile.close()
                        delIaasRole = delIaasTemplate % userDN
                        os.system("printf  \"" + delIaasRole + "\" | ldapmodify -x -D \""+ bind_dn + "\" -w " + bind_pwd)
                    os.system("ldapdelete -x -D \""+ bind_dn + "\" -w " + bind_pwd + "\"" + userDN +"\"")
                    return dumps("web failure")

            f_user_group = file(TEMPLATE_PATH+"userGroup.template","r+")
            userGroupTemplate = f_user_group.read()
            f_user_group.close()
            print userGroupTemplate
            userGroup = userGroupTemplate % uid
            print userGroup
            res = os.system("printf  \"" + userGroup + "\" | ldapmodify -x -D \""+ bind_dn + "\" -w " + bind_pwd)
            if res != 0:
                if enable_web_paas != 0:
                    delWebFile = file(TEMPLATE_PATH+"delWebRole.template","r+")
                    delWebTemplate = delWebFile.read()
                    delWebFile.close()
                    delWebRole = delWebTemplate % userDN
                    os.system("printf  \"" + delWebRole + "\" | ldapmodify -x -D \""+ bind_dn + "\" -w " + bind_pwd)

                if enable_hpc_paas != 0:
                    delHPCFile = file(TEMPLATE_PATH+"delHPCRole.template","r+")
                    delHPCTemplate = delHPCFile.read()
                    delHPCFile.close()
                    delHPCRole = delHPCTemplate % userDN
                    os.system("printf  \"" + delHPCRole + "\" | ldapmodify -x -D \""+ bind_dn + "\" -w " + bind_pwd)

                if enable_iaas != 0:
                    delIaasFile = file(TEMPLATE_PATH+"delIaasRole.template","r+")
                    delIaasTemplate = delIaasFile.read()
                    delIaasFile.close()
                    delIaasRole = delIaasTemplate % userDN
                    os.system("printf  \"" + delIaasRole + "\" | ldapmodify -x -D \""+ bind_dn + "\" -w " + bind_pwd)
                os.system("ldapdelete -x -D \""+ bind_dn + "\" -w " + bind_pwd + "\"" + userDN +"\"" )
                return dumps("usergroup failure")

            uidNumberFile = os.popen("ldapsearch -x -b \""+ uid_number_dn + "\" | grep uidNumber")
            temp = uidNumberFile.read()
            uidNumberFile.close()
            uidNumber = int(temp[temp.find(":")+1:len(temp)-1].strip())
            updateUidFile = file(TEMPLATE_PATH+"nextUidNumber.template","r+")
            updateUidTemp = updateUidFile.read()
            updateUidFile.close()
            updateUid = updateUidTemp % (uidNumber,uidNumber+1)
            print updateUidTemp
            print updateUid
            res = os.system("printf \""+updateUid+"\" | ldapmodify -x -D \""+ bind_dn + "\" -w " + bind_pwd)
            if res != 0:
                if enable_web_paas != 0:
                    delWebFile = file(TEMPLATE_PATH+"delWebRole.template","r+")
                    delWebTemplate = delWebFile.read()
                    delWebFile.close()
                    delWebRole = delWebTemplate % userDN
                    os.system("printf  \"" + delWebRole + "\" | ldapmodify -x -D \""+ bind_dn + "\" -w " + bind_pwd)

                if enable_hpc_paas != 0:
                    delHPCFile = file(TEMPLATE_PATH+"delHPCRole.template","r+")
                    delHPCTemplate = delHPCFile.read()
                    delHPCFile.close()
                    delHPCRole = delHPCTemplate % userDN
                    os.system("printf  \"" + delHPCRole + "\" | ldapmodify -x -D \""+ bind_dn + "\" -w " + bind_pwd)

                if enable_iaas != 0:
                    delIaasFile = file(TEMPLATE_PATH+"delIaasRole.template","r+")
                    delIaasTemplate = delIaasFile.read()
                    delIaasFile.close()
                    delIaasRole = delIaasTemplate % userDN
                    os.system("printf  \"" + delIaasRole + "\" | ldapmodify -x -D \""+ bind_dn + "\" -w " + bind_pwd)
                os.system("ldapdelete -x -D \""+ bind_dn + "\" -w " + bind_pwd + "\"" + userDN +"\"" )
                return dumps("update uidnumber failure")

            updateUidNumberFile = file(TEMPLATE_PATH+"uidNumber.template","r+")
            temp = updateUidNumberFile.read()
            updateUidNumberFile.close()
            updateUidNumber = temp % (uid,uidNumber)
            os.system("printf \""+updateUidNumber+"\" | ldapmodify -x -D \""+ bind_dn + "\" -w " + bind_pwd)
            #send_task("iaas.user_create",(uid,)).wait(None)
            return dumps("registration successful")
        else:
            return dumps("add user failure")

    def new(self, format='json'):
        """GET /users/new: Form to create a new item"""
        # url('new_user')

    def update(self, id):
        """PUT /users/id: Update an existing item"""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="PUT" />
        # Or using helpers:
        #    h.form(url('user', id=ID),
        #           method='put')
        # url('user', id=ID)

    def delete(self, id):
        """DELETE /users/id: Delete an existing item"""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="DELETE" />
        # Or using helpers:
        #    h.form(url('user', id=ID),
        #           method='delete')
        # url('user', id=ID)

    def show(self, id, format='json'):
        """GET /users/id: Show a specific item"""
        # url('user', id=ID)

    def edit(self, id, format='json'):
        """GET /users/id/edit: Form to edit an existing item"""
        # url('edit_user', id=ID)
